import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:ymt/db/offline_database_provider.dart';
import 'package:ymt/utils/image.dart';

class DownloadPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _PageState();
  }
}

class _PageState extends State<DownloadPage>{

  var _progress;
  var _curCount = 0;
  var _count = 0;

  bool _disposed = false;

  @override
  void initState() {
    OfflineDatabaseProvider().open((Database db) async {
      List<Map> products = await db.query(OfflineDatabaseProvider.TABLE_PRODUCTS);
      List<Map> pictures = await db.query(OfflineDatabaseProvider.TABLE_PICTURES);
      _count = pictures.length + products.length;
      print("主图：${products.length},总图：${pictures.length}");
      for (int i = 0; i < products.length; i++) {
        if (_disposed) {
          break;
        }
        var item = products[i];
        var thumbFile = await CacheImage.download(item["thumb_picture"]);
        var mainFile = await CacheImage.download(item["main_picture"]);
        _progress = i/_count;
        _curCount++;
        if (mounted) {
          setState(() {});
        }
        print("$_progress下载:缩略图$thumbFile，原图$mainFile");
      }
      for (int i = products.length; i < _count; i++) {
        if(_disposed){
          break;
        }
        var item = pictures[i];
        var url = "http://nkjjq.cn/uploads/picture/file/${item["id"]}/${item["file"]}";
        var file = await CacheImage.download(url);
        _progress = i/_count;
        _curCount++;
        if (mounted) {
          setState(() {});
        }
        print("$_progress下载$file");
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Widget content;
    var text = Container(
      child: Text("下载图片$_curCount/$_count", style: TextStyle(color: Colors.white, fontSize: 14),),
      margin: EdgeInsets.all(20),);
    content = Column(
      children: <Widget>[LinearProgressIndicator(value: _progress,), text],
      mainAxisAlignment: MainAxisAlignment.center,);
    return Container(child: content,margin: EdgeInsets.only(left: 25, right: 25),);
  }

  @override
  void dispose() {
    _disposed = true;
    super.dispose();
  }

}